package com.woniu.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import java.util.stream.Collectors;
import com.woniu.client.AccountClient;
import com.woniu.client.VenueClient;
import com.woniu.commons.exception.YogaException;
import com.woniu.commons.model.Result;
import com.woniu.commons.model.StateData;
import com.woniu.dao.mapper.YClassTypeMapper;
import com.woniu.dao.mapper.YPersonalClassMapper;
import com.woniu.dao.mapper.YUserPersonalClassMarginMapper;
import com.woniu.model.VenueCoachDto;
import com.woniu.model.YCoach;
import com.woniu.model.dto.LoadListByPersonalCLassDto;
import com.woniu.model.dto.PersonalClassDto;
import com.woniu.model.model.YClassType;
import com.woniu.model.model.YPersonalClass;
import com.woniu.model.model.YUserPersonalClassMargin;
import com.woniu.model.param.CoachByPagePersonalParam;
import com.woniu.model.param.CoachByPersonalParam;
import com.woniu.model.param.CoachPagePersonalClassParam;
import com.woniu.model.param.PersonalClassAddParam;
import com.woniu.model.param.PersonalClassUpdateStateParam;
import com.woniu.service.YPersonalClassService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 吴彦祖
 * @since 2024年05月23日
 */
@Service
public class YPersonalClassServiceImpl extends ServiceImpl<YPersonalClassMapper, YPersonalClass> implements YPersonalClassService {

    @Resource
    private YPersonalClassMapper personalClassMapper;
    @Resource
    private AccountClient accountClient;
    @Resource
    private VenueClient venueClient;
    @Resource
    private YClassTypeMapper classTypeMapper;
    @Resource
    private YUserPersonalClassMarginMapper userPersonalClassMarginMapper;


    /**
     * 修改私课状态为可预约
     *
     * @param
     * @return
     * @throws YogaException
     */
    @Override
    public void updatePersonalClassState(Integer personalClassId) throws YogaException {

        YPersonalClass yPersonalClass = personalClassMapper.selectById(personalClassId);

        if (yPersonalClass==null){
            throw new YogaException(500,"无这个私课");
        }
        // 检查记录的状态
        if (yPersonalClass.getPersonalClassState() == 1) {
            throw new YogaException(500, "该课已是可预约状态");
        }

        // 更新记录的状态
        yPersonalClass.setPersonalClassState(1);
        personalClassMapper.updateById(yPersonalClass);
    }

    /**
     * 传私教课ID查询一个私教课回去
     *
     * @param id：私教课id
     * @return
     * @throws YogaException
     */
    @Override
    public YPersonalClass byIdPersonal(Integer id) throws YogaException {
        YPersonalClass yPersonalClass = personalClassMapper.selectById(id);

        if (yPersonalClass == null || yPersonalClass.getPersonalClassState().equals(StateData.PERSONAL_CLASS_STATE_DISABLED)) {
            throw new YogaException(500, "私课不存在或已下架");
        }

        return yPersonalClass;
    }

    /**
     * 删除私课
     *
     * @param ：leagueClassId：私课id
     * @return
     * @throws YogaException
     */
    @Override
    public void deletePersonalClassState(Integer personalClassId) throws YogaException {
        YPersonalClass yPersonalClass = personalClassMapper.selectById(personalClassId);
        if (yPersonalClass == null) {
            throw new YogaException(500, "删除的私课不存在");
        }
        if (Objects.equals(yPersonalClass.getPersonalClassState(), StateData.PERSONAL_CLASS_STATE_NOT_OK)) {
            throw new YogaException(500, "删除的私课已是删除状态");
        }

        QueryWrapper<YUserPersonalClassMargin> wrapper = new QueryWrapper<>();
        wrapper.eq("personal_class_id",yPersonalClass.getPersonalClassId());
        List<YUserPersonalClassMargin> list = userPersonalClassMarginMapper.selectList(wrapper);

        if (list.size()>0){
        throw new YogaException(500,"还有未上完的课，请上完后删除");
        }

        yPersonalClass.setPersonalClassState(StateData.PERSONAL_CLASS_STATE_NOT_OK);
        personalClassMapper.updateById(yPersonalClass);
    }

    /**
     * 查询私课集合
     *
     * @return
     */
    @Override
    public List loadListPersonalClass() throws YogaException {
        QueryWrapper<YPersonalClass> wrapper = new QueryWrapper<>();
        wrapper.ne("personal_class_state", 0);
        List<YPersonalClass> list = personalClassMapper.selectList(wrapper);
        return list;
    }

    /**
     * 通过教练Id查该教练的私课
     *
     * @param coachId：教练id
     * @return
     */
    @Override
    public List CoachByIdPersonalClass(Integer coachId) throws YogaException {
        QueryWrapper<YPersonalClass> wrapper = new QueryWrapper<>();
        wrapper.eq("coach_id", coachId);
        List<YPersonalClass> yPersonalClassClasses = personalClassMapper.selectList(wrapper);
        return yPersonalClassClasses;
    }

    /**
     * 通过token查该教练的私课
     *
     * @param param
     * @return
     */
    @Override
    public Page<PersonalClassDto> CoachByPageIdPersonalClass(CoachByPagePersonalParam param) throws YogaException {
        if (param.getPageNum() == null) {
            param.setPageNum(1);
        }
        if (param.getPageSize() == null) {
            param.setPageSize(5);
        }

        QueryWrapper<YPersonalClass> wrapper = new QueryWrapper<>();
        wrapper.eq("coach_id", param.getCoachId());
        wrapper.ne("personal_class_state",2);//2是已删除的课

        Page<YPersonalClass> classPage = baseMapper.selectPage(new Page<>(param.getPageNum(), param.getPageSize()), wrapper);


        Page<PersonalClassDto> page = new Page<>();
        page.setCurrent(classPage.getCurrent());
        page.setOptimizeCountSql(classPage.optimizeCountSql());
        page.setPages(classPage.getPages());
        page.setSearchCount(classPage.searchCount());
        page.setSize(classPage.getSize());
        page.setTotal(classPage.getTotal());

        ArrayList<PersonalClassDto> dto = new ArrayList<>();

        for (YPersonalClass personalClass:classPage.getRecords()){

            PersonalClassDto pageDto = BeanUtil.toBean(personalClass, PersonalClassDto.class);

            //通过教练ID查出教练名字赋值给dto
            String coachName = accountClient.byId(personalClass.getCoachId()).getData().getCoachName();
            if (coachName == null){
                throw new YogaException(500,"请先招募教练");
            }
            pageDto.setCoachName(coachName);

            //通过课程类型id查出课程类型名字
            YClassType yClassType = classTypeMapper.selectById(personalClass.getClassTypeId());
            if (yClassType==null){
                throw new YogaException(500,"类型不存在");
            }
            pageDto.setClassTypeName(yClassType.getClassTypeName());



            dto.add(pageDto);
        }
        page.setRecords(dto);

        return page;
    }

    @Override
    public Page<PersonalClassDto> CoachPagePersonalClass(CoachPagePersonalClassParam param) {
        if (param.getPageNum() == null) {
            param.setPageNum(1);
        }
        if (param.getPageSize() == null) {
            param.setPageSize(5);
        }

        List<VenueCoachDto> dtos = venueClient.loadVenueCoachByVenueId(param.getVenueId()).getData();
        Set<Integer> coachIds = dtos.stream().map(o -> o.getCoachId()).collect(Collectors.toSet());

        QueryWrapper<YPersonalClass> wrapper = new QueryWrapper<>();
        wrapper.in("coach_id", coachIds);
        wrapper.ne("personal_class_state",2);//2是已删除的课

        Page<YPersonalClass> classPage = baseMapper.selectPage(new Page<>(param.getPageNum(), param.getPageSize()), wrapper);


        Page<PersonalClassDto> page = new Page<>();
        page.setCurrent(classPage.getCurrent());
        page.setOptimizeCountSql(classPage.optimizeCountSql());
        page.setPages(classPage.getPages());
        page.setSearchCount(classPage.searchCount());
        page.setSize(classPage.getSize());
        page.setTotal(classPage.getTotal());

        ArrayList<PersonalClassDto> dto = new ArrayList<>();

        for (YPersonalClass personalClass:classPage.getRecords()){

            PersonalClassDto pageDto = BeanUtil.toBean(personalClass, PersonalClassDto.class);

            //通过教练ID查出教练名字赋值给dto
            String coachName = accountClient.byId(personalClass.getCoachId()).getData().getCoachName();
            if (coachName == null){
                throw new YogaException(500,"请先招募教练");
            }
            pageDto.setCoachName(coachName);

            //通过课程类型id查出课程类型名字
            YClassType yClassType = classTypeMapper.selectById(personalClass.getClassTypeId());
            if (yClassType==null){
                throw new YogaException(500,"类型不存在");
            }
            pageDto.setClassTypeName(yClassType.getClassTypeName());



            dto.add(pageDto);
        }
        page.setRecords(dto);

        return page;
    }

    @Override
    public LoadListByPersonalCLassDto loadListByPersonalClass(String coachName) {

        QueryWrapper<YPersonalClass> wrapper = new QueryWrapper<>();
        wrapper.ne("personal_class_state", 0);

        List<YPersonalClass> list = personalClassMapper.selectList(wrapper);

        LoadListByPersonalCLassDto dto = new LoadListByPersonalCLassDto();

        return dto;
    }

    @Override
    public Page<PersonalClassDto> VenueByPageIdPersonalClass(CoachByPersonalParam param) throws YogaException {
        if (param.getPageNum() == null) {
            param.setPageNum(1);
        }
        if (param.getPageSize() == null) {
            param.setPageSize(5);
        }

        List<VenueCoachDto> list = venueClient.VenueByIdCoach(param.getVenueId()).getData();


        // 提取每个 coachId
        List<Integer> coachIds = list.stream().map(VenueCoachDto::getCoachId).collect(Collectors.toList());


        Page<PersonalClassDto> page = new Page<>();
        ArrayList<PersonalClassDto> dto = new ArrayList<>();

        for (Integer coachId : coachIds) {
            QueryWrapper<YPersonalClass> wrapper = new QueryWrapper<>();
            wrapper.eq("coach_id", coachId);
            wrapper.ne("personal_class_state",2);//2是已删除的课

            Page<YPersonalClass> classPage = baseMapper.selectPage(new Page<>(param.getPageNum(), param.getPageSize()), wrapper);



            page.setCurrent(classPage.getCurrent());
            page.setOptimizeCountSql(classPage.optimizeCountSql());
            page.setPages(classPage.getPages());
            page.setSearchCount(classPage.searchCount());
            page.setSize(classPage.getSize());
            page.setTotal(classPage.getTotal());



            for (YPersonalClass personalClass:classPage.getRecords()){

            PersonalClassDto pageDto = BeanUtil.toBean(personalClass, PersonalClassDto.class);

            //通过教练ID查出教练名字赋值给dto
            String coachName = accountClient.byId(personalClass.getCoachId()).getData().getCoachName();
            if (coachName == null){
                throw new YogaException(500,"请先招募教练");
            }
            pageDto.setCoachName(coachName);

            //通过课程类型id查出课程类型名字
            YClassType yClassType = classTypeMapper.selectById(personalClass.getClassTypeId());
            if (yClassType==null){
                throw new YogaException(500,"类型不存在");
            }
            pageDto.setClassTypeName(yClassType.getClassTypeName());


            dto.add(pageDto);
        }

        }
        page.setRecords(dto);
        return page;
    }


//@Override
//public Page<PersonalClassDto> VenueByPageIdPersonalClass(CoachByPersonalParam param) throws YogaException {
//    if (param.getPageNum() == null) {
//        param.setPageNum(1);
//    }
//    if (param.getPageSize() == null) {
//        param.setPageSize(5);
//    }
//
//    // 获取教练列表
//    List<VenueCoachDto> list = venueClient.VenueByIdCoach(param.getVenueId()).getData();
//    System.out.println(list);
//
//    // 提取每个 coachId
//    List<Integer> coachIds = list.stream().map(VenueCoachDto::getCoachId).collect(Collectors.toList());
//    System.out.println(coachIds);
//
//    // 初始化最终结果分页对象
//    Page<PersonalClassDto> resultPage = new Page<>();
//    resultPage.setCurrent(param.getPageNum());
//    resultPage.setSize(param.getPageSize());
//
//    List<PersonalClassDto> dtoList = new ArrayList<>();
//
//    // 遍历教练ID，分别获取他们的课程信息
//    for (Integer coachId : coachIds) {
//        QueryWrapper<YPersonalClass> wrapper = new QueryWrapper<>();
//        wrapper.eq("coach_id", coachId);
//        wrapper.ne("personal_class_state", 2); // 2是已删除的课
//
//        Page<YPersonalClass> classPage = baseMapper.selectPage(new Page<>(param.getPageNum(), param.getPageSize()), wrapper);
//
//        for (YPersonalClass personalClass : classPage.getRecords()) {
//            PersonalClassDto pageDto = BeanUtil.toBean(personalClass, PersonalClassDto.class);
//
//            // 通过教练ID查出教练名字赋值给dto
//            String coachName = accountClient.byId(personalClass.getCoachId()).getData().getCoachName();
//            if (coachName == null) {
//                throw new YogaException(500, "请先招募教练");
//            }
//            pageDto.setCoachName(coachName);
//
//            // 通过课程类型id查出课程类型名字
//            YClassType yClassType = classTypeMapper.selectById(personalClass.getClassTypeId());
//            if (yClassType == null) {
//                throw new YogaException(500, "类型不存在");
//            }
//            pageDto.setClassTypeName(yClassType.getClassTypeName());
//
//            dtoList.add(pageDto);
//        }
//
//        // 合并分页信息
//        if (resultPage.getTotal() == 0) {
//            resultPage.setTotal(classPage.getTotal());
//            resultPage.setPages(classPage.getPages());
//        }
//    }
//
//    resultPage.setRecords(dtoList);
//
//    return resultPage;
//}



    /**
     * 新增私课
     *
     * @param param：coachId：教练；price：价格；minute：分钟数（课程时长）；classTypeId：课程类型id
     * @return
     * @throws YogaException
     */
    @Override
    public void addPersonalClass(PersonalClassAddParam param) throws YogaException {
        Result<YCoach> yCoachResult = accountClient.byId(param.getCoachId());
        YCoach yCoach = yCoachResult.getData();
        if (yCoach == null) {
            throw new YogaException(500, "教练不存在，请重新选择");
        }
        if (param.getPrice().compareTo(BigDecimal.ZERO) <= 0) {
            throw new YogaException(500, "输入价格有误，请重新输入");
        }
        Integer classTypeId = param.getClassTypeId();
        YClassType yClassType = classTypeMapper.selectById(classTypeId);
        if (yClassType == null) {
            throw new YogaException(500, "课程类型不存在，请重新选择");
        }
        if (!Objects.equals(yClassType.getClassTypeState(), StateData.CLASS_TYPE_STATE_START)) {
            throw new YogaException(500, "课程类型状态有误，请重新选择");
        }

        YPersonalClass personalClass = new YPersonalClass();
        personalClass.setCoachId(param.getCoachId());
        personalClass.setPrice(param.getPrice());
        personalClass.setMinute(param.getMinute());
        personalClass.setPersonalClassState(StateData.PERSONAL_CLASS_STATE_DISABLED);//新增状态写的0，后续教练自己修改成可预约
        personalClass.setClassTypeId(param.getClassTypeId());

        personalClassMapper.insert(personalClass);
    }


}
